const sqlExcute = require("../../database/live/query")
const vodExcute = require("../../database/vod/query")
const fs = require("fs")
const path = require("path")
const dayjs = require("dayjs")

// 获取直播列表
const getLiveList = async (req, res) => {
  const { page, limit } = req.params
  const sql = `SELECT * FROM live_course WHERE is_deleted = 0 ORDER BY create_time DESC LIMIT ${(page - 1) * limit}, ${limit}`
  const result = await sqlExcute(sql)
  // 查询总数
  const totalSql = `SELECT COUNT(*) AS total FROM live_course WHERE is_deleted = 0`
  const totalResult = await sqlExcute(totalSql)
  const total = totalResult[0].total
  // 查询讲师
  for (const item of result) {
    const teacherSql = `SELECT * FROM teacher WHERE id = ${item.teacher_id}`
    const teacherResult = await vodExcute.sqlExcute(teacherSql)
    item.param = teacherResult[0]
  }

  res.send({
    status: 1,
    code: 20000,
    data: {
      records: result,
      total
    }
  })
}

// 根据id获取直播课程信息
const getById = async (req, res) => {
  const { id } = req.params
  const sql = `SELECT * FROM live_course WHERE id = ${id} and is_deleted = 0`
  const result = await sqlExcute(sql)
  // 查询讲师
  const teacherSql = `SELECT * FROM teacher WHERE id = ${result[0].teacher_id}`
  const teacherResult = await vodExcute.sqlExcute(teacherSql)
  result[0].param = teacherResult[0]
  // 查询直播课程详情
  const liveDetailSql = `SELECT * FROM live_course_description WHERE live_course_id = ${id}`
  result[0].description = (await sqlExcute(liveDetailSql))[0].description

  res.send({
    status: 1,
    code: 20000,
    data: result[0]
  })
}

// 直播封面图片上传
const upload = async (req, res) => {
  const oldName = req.file.path
  const originalname = req.file.originalname
  const newName = path.join(__dirname, "../../public/upload/live", originalname)
  fs.renameSync(oldName, newName)//将老的文件名改成新的有后缀的文件 #同步写法

  res.send({
    status: 1,
    code: 20000,
    data: 'http://127.0.0.1:8080/uploads/live/' + originalname
  })
}

// 更新直播课程信息
const updateById = async (req, res) => {
  const liveCourse = req.body
  const { id, teacher_id, description } = liveCourse
  // 删除一些不需要的字段
  delete liveCourse.id
  delete liveCourse.course_id
  delete liveCourse.create_time
  delete liveCourse.description
  delete liveCourse.param

  liveCourse.start_time = dayjs(liveCourse.start_time).format("YYYY-MM-DD HH:mm:ss")
  liveCourse.end_time = dayjs(liveCourse.end_time).format("YYYY-MM-DD HH:mm:ss")
  liveCourse.update_time = dayjs(liveCourse.update_time).format("YYYY-MM-DD HH:mm:ss")

  // 更新直播课程信息
  const sqlDesc = 'UPDATE live_course_description SET ? WHERE live_course_id = ?'
  const resultDesc = await sqlExcute(sqlDesc, [{description}, id])

  const sql = `UPDATE live_course SET ? WHERE id = ${id}`
  const result = await sqlExcute(sql, liveCourse)
  res.send({
    status: 1,
    code: 20000,
    message: '更新成功',
    data: result
  })
}

// 添加直播课程
const save = async (req, res) => {
  const liveCourse = req.body
  const { password, description } = liveCourse
  // 删除一些不需要的字段
  delete liveCourse.id
  delete liveCourse.course_id
  delete liveCourse.create_time
  delete liveCourse.description
  delete liveCourse.param
  delete liveCourse.password
  // 过滤掉空字段
  for (const key in liveCourse) {
    if (liveCourse[key] === '') {
      delete liveCourse[key]
    }
  }

  liveCourse.start_time = dayjs(liveCourse.start_time).format("YYYY-MM-DD HH:mm:ss")
  liveCourse.end_time = dayjs(liveCourse.end_time).format("YYYY-MM-DD HH:mm:ss")
  liveCourse.create_time = new Date()

  // 添加直播课程信息
  const sql = `INSERT INTO live_course SET ?`
  const result = await sqlExcute(sql, liveCourse)
  console.log(result)

  // 插入直播课程信息
  const sqlDesc = 'INSERT INTO live_course_description SET ?'
  let descInfo = {
    description,
    live_course_id: result.insertId
  }
  const resultDesc = await sqlExcute(sqlDesc, descInfo   )

  res.send({
    status: 1,
    code: 20000,
    data: result
  })
}

// 删除直播课程
const removeById = async (req, res) => {
  const { id } = req.params
  const sql = `UPDATE live_course SET is_deleted = 1 WHERE id = ${id}`
  const result = await sqlExcute(sql)
  res.send({
    status: 1,
    code: 20000,
    data: result
  })
}

// 获取直播账号
const getLiveCourseAccount = async (req, res) => {
  const { id } = req.params
  const sql = `SELECT * FROM live_course_account WHERE live_course_id = ${id}`
  const result = await sqlExcute(sql)
  console.log(sql)
  console.log(result)
  res.send({
    status: 1,
    code: 20000,
    data: result[0]
  })
}

// 获取配置
const getLiveCourseConfig = async (req, res) => {
  const { id } = req.params
  const sql = `SELECT * FROM live_course_config WHERE live_course_id = ${id}`
  const result = await sqlExcute(sql)
  // 获取直播商品
  const sqlGoods = `SELECT * FROM live_course_goods WHERE live_course_id = ${id} AND is_deleted = 0`
  result[0].liveCourseGoodsList = await sqlExcute(sqlGoods)

  res.send({
    status: 1,
    code: 20000,
    data: result[0]
  })
}

// 更新配置
const updateCourseConfig = async (req, res) => {
  const liveCourseConfig = req.body
  const { id } = liveCourseConfig
  const { live_course_id } = liveCourseConfig
  const liveCourseGoodsList = liveCourseConfig.liveCourseGoodsList
  // 获取商品id集合
  const goodsIdList = []
  liveCourseGoodsList.forEach(item => {
    if (item.id) {
      goodsIdList.push(item.id)
    }
    delete item.id;
    item.create_time = dayjs(item.create_time).format("YYYY-MM-DD HH:mm:ss")
    item.update_time = dayjs(item.update_time).format("YYYY-MM-DD HH:mm:ss")
  })

  // 删除一些不需要的字段
  delete liveCourseConfig.id
  delete liveCourseConfig.live_course_id
  delete liveCourseConfig.create_time
  delete liveCourseConfig.update_time
  delete liveCourseConfig.liveCourseGoodsList

  // 过滤掉空字段
  for (const key in liveCourseConfig) {
    if (liveCourseConfig[key] === '') {
      delete liveCourseConfig[key]
    }
  }

  // 更新直播课程配置
  const sql = `UPDATE live_course_config SET ? WHERE id = ${id}`
  const result = await sqlExcute(sql, liveCourseConfig)

  // 删除直播商品
  const deleteSql = ` AND id NOT IN (${goodsIdList.join(',')})`
  let sqlGoods = `update live_course_goods set is_deleted=1 WHERE live_course_id = ${live_course_id}`
  if (goodsIdList.length > 0) {
    sqlGoods += deleteSql
  }
  const goodsResult = await sqlExcute(sqlGoods)
  console.log(sqlGoods)

  // 添加直播商品
  const sqlGoodsAdd = `INSERT INTO live_course_goods SET ?`
  for (const item of liveCourseGoodsList) {
    const goodsInfo = {
      live_course_id,
      ...item,
    }
    const resultGoods = await sqlExcute(sqlGoodsAdd, goodsInfo)
  }

  res.send({
    status: 1,
    code: 20000,
    message: '更新成功',
    data: result
  })
}

module.exports = {
  getLiveList,
  getById,
  updateById,
  upload,
  save,
  removeById,
  getLiveCourseAccount,
  getLiveCourseConfig,
  updateCourseConfig
}
